package cn.turboinfo.fuyang.api.gateway.mini.framework.http.interceptor;

import cn.turboinfo.fuyang.api.entity.common.enumeration.user.UserType;
import cn.turboinfo.fuyang.api.gateway.mini.constant.MiniRestConstants;
import cn.turboinfo.fuyang.api.gateway.mini.framework.http.context.MiniRequestContext;
import cn.turboinfo.fuyang.api.gateway.mini.framework.http.context.MiniRequestContextHolder;
import cn.turboinfo.fuyang.api.gateway.web.framework.http.annotation.CompanyScope;
import cn.turboinfo.fuyang.api.gateway.web.framework.http.interceptor.BaseHandlerInterceptorAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestParameterTypeBinding;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 家政企业用户拦截
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class MiniCompanyScopeInterceptor extends BaseHandlerInterceptorAdapter {

    private final AutoMappingRequestParameterTypeBinding autoMappingRequestParameterTypeBinding;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            MiniRequestContext requestContext = MiniRequestContextHolder.current();
            if (requestContext.isLogin()) {
                Optional<CompanyScope> companyScopeOptional = getAnnotation(handlerMethod, CompanyScope.class, true);
                CompanyScope annotation = companyScopeOptional.orElseGet(() -> autoMappingRequestParameterTypeBinding.getAnnotation(handlerMethod.getMethod(), CompanyScope.class, true));

                if (annotation != null) {
                    if (!StringUtils.equals(request.getHeader(MiniRestConstants.HEADER_USER_TYPE), String.valueOf(UserType.Company.getValue()))) {
                        throw new RuntimeException("当前请求用户类型不正确");
                    }

                    try {
                        long companyId = Long.parseLong(request.getHeader(MiniRestConstants.HEADER_USER_TYPE_OBJECT));
                        if (companyId <= 0) {
                            throw new RuntimeException("非法请求的家政企业编码");
                        }
                        if (requestContext.getUserTypeRelList()
                                .stream()
                                .filter(userTypeRel -> userTypeRel.getUserType() == UserType.Company)
                                .filter(userTypeRel -> userTypeRel.getObjectId() == companyId)
                                .findAny().isEmpty()) {
                            throw new RuntimeException("当前请求用户不是家政企业管理用户");
                        }
                        requestContext.setUserType(UserType.Company);
                        requestContext.setCompanyId(companyId);
                    } catch (NumberFormatException e) {
                        throw new RuntimeException("请求的家政企业编码不正确");
                    }
                }
            }
        }
        return true;
    }

}
